package org.goldfish.cookied_chatroom02.servlet;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.goldfish.cookied_chatroom02.entity.RegisteringUserBean;
import org.goldfish.cookied_chatroom02.entity.UserBean;
import org.goldfish.cookied_chatroom02.model.LoginParams;
import org.goldfish.cookied_chatroom02.model.RegisterManager;
import org.goldfish.cookied_chatroom02.model.RegisterManagerImpl;

import java.io.IOException;
import java.util.Objects;

@WebServlet(name = "register", value = "/register")
public class RegisterServlet extends HttpServlet implements LoginParams {
    RegisterManager manager;

    public void init() {
        manager = new RegisterManagerImpl();

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserBean bean = manager.getUserBeanFromCookies(req.getCookies());
        if (bean != null) {
            manager.warnOverwriteExistingUser(resp, bean);
        }
        Objects.requireNonNull(manager.register(req)).forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserBean bean = manager.getUserBeanFromPostInputStream(req.getInputStream());
        RequestDispatcher dispatcher = manager.login(req);
        TRY:
        {
            if (bean instanceof RegisteringUserBean) {
                manager.warn(((RegisteringUserBean) bean).getException().getMessage(), req);
                dispatcher = manager.register(req);
                break TRY;
            }
            if (!manager.writeUserBeanToCookie(resp, bean)) {
                manager.warn("保存用户信息失败", req);
                dispatcher = manager.register(req);
                break TRY;
            }
            if (!manager.writeUserBeanToDB(bean)) {
                manager.warn("注册失败，要不换个用户名试试", req);
                dispatcher = manager.register(req);
                break TRY;
            }
            manager.warn("注册成功", req);
        }
        dispatcher.forward(req, resp);
    }
}
